package com.tsystems.train.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.tsystems.train.entity.User;
import com.tsystems.train.entity.Ticket;
import com.tsystems.train.entity.TimeTableElement;

@Stateless
public class TicketDAO extends AbstractDAO<Ticket> {

	public List<Ticket> getTickestByTTE(TimeTableElement timeTableElement) {

		EntityManager em = getEntityManager();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> tickets = criteria.from(Ticket.class);
		criteria.select(tickets);
		criteria.where(builder.equal(tickets.get("timeTableElement").get("id"),
				timeTableElement.getId()));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return result;
	}

	public List<Ticket> getTicketsByPassenger(User user) {

		EntityManager em = getEntityManager();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> tickets = criteria.from(Ticket.class);
		criteria.select(tickets);
		criteria.where(builder.equal(tickets.get("user").get("id"),
				user.getId()));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return result;
	}

	public Ticket getTicketsByPassengerAndTTE(User user,
			TimeTableElement element) {

		EntityManager em = getEntityManager();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> tickets = criteria.from(Ticket.class);
		criteria.select(tickets);
		criteria.where(builder.and(builder.equal(
				tickets.get("user").get("id"), user.getId()), builder
				.equal(tickets.get("timeTableElement").get("id"),
						element.getId())));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return !result.isEmpty() ? result.get(0) : null;
	}

	public List<Ticket> getTicketsByTrain(TimeTableElement timeTableElement) {

		EntityManager em = getEntityManager();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> ticket = criteria.from(Ticket.class);
		criteria.select(ticket);
		criteria.where(builder.equal(ticket.get("timeTableElement").get("id"),
				timeTableElement.getId()));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return result;
	}

	/**
	 * Небезопасное добавление билета в базу, оборачивание в транзакцию отдается
	 * на откуп вызывающей функции
	 * 
	 * @param ticket
	 *            -Билет который необходимо добавить в базу.
	 */
	/*
	 * public void insertNotSafe(Ticket ticket) {
	 * TrainsEntityManager.getInstance().persist(ticket); }
	 */

}
